import { reqLogin } from "../../request/api"
//初始值
const initState = {
    user: {
        phone: "",
        password: ""
    },
    //用户信息
    info: sessionStorage.getItem("info") ? JSON.parse(sessionStorage.getItem("info")) : {}
}

//actionTypes
const types = {
    //修改 
    CHANGE_USER: "LOGIN_CHANGE_USER",
    CHANGE_INFO: "LOGIN_CHANGE_INFO"
}

//reducer 修改数据
const reducer = (state = initState, action) => {
    switch (action.type) {
        case types.CHANGE_USER:
            return {
                ...state,
                user: {
                    ...state.user,
                    [action.key]: action.value
                }
            }
        case types.CHANGE_INFO:
            return {
                ...state,
                info: action.info
            }
        default:
            return state;
    }

}

//actionCreators组件派发任务
export const actions = {
    //修改，请求
    changeUser: (key, value) => ({ type: types.CHANGE_USER, key, value }),
    changeInfo: (info,history) => {
        if (info.token) {
            sessionStorage.setItem("info", JSON.stringify(info))
        } else {
            sessionStorage.removeItem("info")
            sessionStorage.removeItem("islogin")
            history.push("/login")
            alert("您已退出登录！！！！")
            history.go(0)
        }
        return { type: types.CHANGE_INFO, info }
    },
    reqLogin: (history) => (dispatch, getState) => {
        let { user } = getState().login
        reqLogin(user).then(res => {
            if (res.data.code === 200) {
                let { phone, password } = user
                if (phone === "admin" && password === "123") {
                    dispatch(actions.changeInfo(res.data.list))
                    sessionStorage.setItem("islogin", 1)
                    dispatch(actions.changeUser(null,null))
                    history.push("/index")
                    
                }

            }
        })
    }

}

//selectors 导出数据
export const getUser = state => state.login.user;
export const getInfo = state => state.login.info

export default reducer